package org.openwebtop.common.security;

import org.apache.commons.lang.StringUtils;
import org.openwebtop.sunshine.dao.UserDAO;
import org.openwebtop.sunshine.domain.PermissionType;
import org.openwebtop.sunshine.domain.User;
import org.openwebtop.sunshine.domain.UserPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.memory.UserAttribute;
import org.springframework.stereotype.Component;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private UserDAO userDAO;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		if (StringUtils.isNotBlank(username)) {
			final User user = userDAO.findById(username);

			if (user != null) {
				final UserAttribute userAttribute = new UserAttribute();
				userAttribute.addAuthority(new GrantedAuthorityImpl("ROLE_USER"));

				for (UserPermission userPermission : user.getUserPermissions()) {
					final PermissionType permission = userPermission.getPermissionType();
					userAttribute.addAuthority(new GrantedAuthorityImpl(permission.toString()));
				}

				return new UserContext(user, userAttribute.getAuthorities(), userAttribute.isEnabled());
			}
		}

		throw new UsernameNotFoundException("not found " + username);
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

}
